import requests
import json
import os
import shutil

path_dir = './json'


def main_fun(code='100000_full'):
    url = 'https://geo.datav.aliyun.com/areas/bound/{}.json'.format(code)
    r = requests.get(url)
    if r.status_code == 200:
        r_json = json.loads(r.text)
        features = r_json['features'] or []
        path = './json/{}.json'.format(code)
        with open(path, 'w', encoding='utf-8-sig', errors='ignore') as file:
            json.dump(r_json, file, ensure_ascii=False, indent=4)

        for item in features:
            if item['properties'].__contains__('childrenNum'):
                if item['properties'].__contains__('name'):
                    print(item['properties']['name'])

                if item['properties']['childrenNum'] > 0:
                    _code = str(item['properties']['adcode']) + '_full'
                    main_fun(_code)
                else:
                    _code = str(item['properties']['adcode'])
                    main_fun(_code)


def create_dir_not_exist(path):
    if not os.path.exists(path):
        os.mkdir(path)
    else:
        shutil.rmtree(path)
        os.mkdir(path)


create_dir_not_exist(path_dir)
main_fun()
